package com.novel.service.impl;


import com.reading.pojo.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BooksService {
    @Autowired
    private MongoTemplate mongoTemplate;

    // 定义常量，用于查询中指定的字段名称
    private static final String FIELD_ID = "id";
    private static final String FIELD_PID = "pid";
    private static final String FIELD_TITLE = "title";
    private static final String FIELD_VIP = "vip";
    private static final String FIELD_STATUS = "status";
    private static final String FIELD_CHAPTER_ID = "chapter_id";
    private static final String FIELD_WORD_COUNT = "word_count";
    private static final String FIELD_UPDATED_AT = "updated_at";

    /**
     * 根据父ID查找所有书籍
     * 此方法用于根据给定的父ID（pid）查询书籍集合中所有匹配的书籍
     * 它通过构建一个查询对象，指定查询条件和所需返回的字段，然后利用mongoTemplate执行查询
     *
     * @param pid 父ID，用于指定查询条件
     * @return 匹配条件的书籍列表
     */
    public List<Book> findall(Integer pid) {
        // 创建一个新的查询对象
        Query query = new Query();
        // 判断条件pid=?
        Criteria criteria = Criteria.where("pid").is(pid);
        query.addCriteria(criteria);
        // 获取指定字段，减少数据传输
        query.fields().include(FIELD_ID, FIELD_PID, FIELD_TITLE, FIELD_VIP, FIELD_STATUS, FIELD_CHAPTER_ID, FIELD_WORD_COUNT, FIELD_UPDATED_AT);
        // 执行查询并返回结果
        return mongoTemplate.find(query, Book.class);
    }

    public  List<Book> findall1(Integer pid,Integer chapterId) {

        Query query = new Query();
        Criteria criteria = Criteria.where("pid").is(pid).and("chapter_id").is(chapterId);
        query.addCriteria(criteria);
//        query.fields().include(FIELD_ID, FIELD_PID, FIELD_TITLE, FIELD_VIP, FIELD_STATUS);
        return mongoTemplate.find(query, Book.class);
    }

    public List<Book> findallbyid(Integer pid) {
        return mongoTemplate.find(new Query(Criteria.where("pid").is(pid)), Book.class);
    }
}